package com.wx.activitys.drp.controller;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.github.sd4324530.fastweixin.api.response.GetUserInfoResponse;
import com.wx.activitys.drp.JsonResult;
import com.wx.activitys.drp.model.BUserInfo;
import com.wx.activitys.drp.service.UserInfoService;

@Controller
@RequestMapping("/login")
public class LoginController {
  @Autowired
  UserInfoService userInfoService;
	
	@RequestMapping(value = "jump.html", method = RequestMethod.GET)
	public String login(HttpServletRequest request, HttpServletResponse response,HttpSession session,Model model){
		GetUserInfoResponse userInfo =((GetUserInfoResponse)request.getSession().getAttribute("userInfo"));
		if(userInfo!=null){
			BUserInfo user=userInfoService.findByOpenid(userInfo.getOpenid());
			if(user !=null){
				BUserInfo buserInfo = userInfoService.findByOpenid(userInfo.getOpenid());
				if (StringUtils.isNotBlank(buserInfo.getAuthInfo())) {
					JSONObject jsStr = JSONObject.parseObject(buserInfo.getAuthInfo());
					model.addAttribute("authInfo", jsStr);
				}
				model.addAttribute("buserInfo", user);
				session.setAttribute("user", user);
				return "drp/user/user";
			}else{
			    return "drp/passwordLogin";
		 }
		}else{
			return "error/error";
		}
	}
	
	
	@RequestMapping(value="smsLogin.html",method = RequestMethod.GET)
	public String pwd(HttpServletRequest request,HttpSession session){
		return "drp/smsLogin";
	}
	
	@RequestMapping(value="pwdLogin.html",method = RequestMethod.GET)
	public String pwd2(HttpServletRequest request,HttpSession session){
		 return "drp/passwordLogin";
	}
	
	@RequestMapping(value="login.html",method = RequestMethod.POST)
	@ResponseBody
	public JsonResult pwd(HttpServletRequest request,@RequestParam Map<String,Object> map,HttpSession session){
		map.put("state", 1);
		List<BUserInfo> bu=userInfoService.selectByMap(map);
		if(bu!=null && bu.size()>0){
			session.setAttribute("user", bu.get(0));
			return JsonResult.success("登录成功", bu);
		}else{
			return JsonResult.fail("号码或密码错误", bu);
		}
	}
	
	/**
	 * 登出
	 */
	@RequestMapping(value = "/logout.html", method = RequestMethod.GET)
	public String out(Model model, HttpSession session, HttpServletRequest request, HttpServletResponse response){
		session.setAttribute("user", null);
		return "drp/passwordLogin";
	}

}
